package com.ict.txmsv2.services;

import com.ict.txmsv2.mapper.EquipmentMapper;
import com.ict.txmsv2.model.Equipment;
import com.ict.txmsv2.utils.OSSutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

/**
 * @author linzzz
 * @desc ...
 * @date 2020-12-19
 */
@Service
public class EquipService {

    @Autowired
    EquipmentMapper equipmentMapper;


    public List<Equipment> getAllEquip() {
        return equipmentMapper.getAllEquip();
    }

    public int delEquip(Integer id) {
        Equipment equipment = equipmentMapper.selectByPrimaryKey(id);
        OSSutils.deleteAvatar(equipment.getEimg());
        return equipmentMapper.deleteByPrimaryKey(id);
    }

    public int updateEquip(Equipment equipment) {
        return equipmentMapper.updateByPrimaryKeySelective(equipment);
    }

    public int addEquips(Equipment equipment, MultipartFile file, int count) {
        InputStream in = null;
        OutputStream os = null;
        int ans = 0;
        String path = "D:\\txms\\temp\\";
        try {
            in = file.getInputStream();
//            in = file;
            byte[] bs = new byte[1024];
            int len;
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(path+ "temp.jpg");
            while ((len = in.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            for (int i = 0; i < count; i++) {
                in = new FileInputStream(path + "temp.jpg");
                String url = OSSutils.uploadEquipPhoto(in);
                equipment.setEname(equipment.getEclass()+"-"+(i+1));
                equipment.setEimg(url);
                ans += equipmentMapper.insertSelective(equipment);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                File f = new File(path+".jpg");
                f.delete();
                os.flush();
                os.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ans;
    }

    public int delMany(Integer[] ids) {
        for (Integer id : ids) {
            OSSutils.deleteAvatar(equipmentMapper.selectByPrimaryKey(id).getEimg());
        }
        return equipmentMapper.delMany(ids);
    }
}
